<template>
  <el-form-item :rules="item.rule" :label="item.label" :prop="item.prop">
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <el-checkbox-group
      v-model="formData[item.prop]"
      @change="handleChange"
      :disabled="item.disabled"
    >
      <el-checkbox
        v-for="child in item.children"
        :label="child.code"
        :key="child.code"
      >
        {{ child.label }}
      </el-checkbox>
    </el-checkbox-group>
  </el-form-item>
</template>

<script>
export default {
  name: "checkboxCom",
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      checkAll: false,
      isIndeterminate: false
    };
  },
  methods: {
    handleCheckAllChange(val) {
      let checkedArray = [];
      this.item.children.forEach(value => {
        checkedArray.push(value.code);
      });
      this.formData[this.item.prop] = val ? checkedArray : [];
      this.isIndeterminate = false;
    },
    handleChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.item.children.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.item.children.length;
      return (
        this.item.change && this.item.change(this.formData[this.item.prop])
      );
    }
  }
};
</script>

<style scoped lang="scss"></style>
